﻿using Sprout.Schedule.Dtos;
using Sprout.Schedule.Enums;
using Sprout.Schedule.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Sprout.Schedule.Jobs
{
    /// <summary>
    /// Api任务基类
    /// </summary>
    public interface IBaseApiJob
    {
        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        Task ExecuteAsync(ApiJobParamsDto dto);
    }

    /// <summary>
    /// Api任务父类
    /// </summary>
    public abstract class ApiJobBase : JobBase, IBaseApiJob
    {

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="dto">任务参数</param>
        /// <returns></returns>
        public virtual async Task ExecuteAsync(ApiJobParamsDto dto)
        {
            TaskId = dto.TaskId;

            try
            {
                await ExecuteAsync();
            }
            catch (Exception e)
            {
                await LogAsync($"执行 Execute 异常：{e.Message}", e);
            }
            finally
            {
                //任务完成
                await JobRunEndAsync();
            }
        }
        /// <summary>
        /// 需要实现的方法，具体业务实现逻辑
        /// </summary>
        /// <returns></returns>
        protected virtual Task ExecuteAsync()
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="dto">任务参数</param>
        /// <returns></returns>
        public virtual void Execute(ApiJobParamsDto dto)
        {
            TaskId = dto.TaskId;

            try
            {
                Execute();
            }
            catch (Exception e)
            {
                Log($"执行 Execute 异常：{e.Message}", e);
            }
            finally
            {
                //任务完成
                JobRunEnd();
            }
        }
        /// <summary>
        /// 需要实现的方法，具体业务实现逻辑
        /// </summary>
        /// <returns></returns>
        protected virtual void Execute()
        {

        }
    }
}
